home *** CD-ROM | disk | FTP | other *** search
- Path: news.Stanford.EDU!not-for-mail
- From: brien@leland.Stanford.EDU (brien oberstein)
- Newsgroups: comp.lang.c++
- Subject: Copy constructing an already default constructed object
- Date: 25 Jan 1996 14:28:27 -0800
- Organization: Stanford University
- Message-ID: <4e906b$stk@elaine32.Stanford.EDU>
- NNTP-Posting-Host: elaine32.stanford.edu
- X-Newsreader: NN version 6.5.0 (NOV)
-
- I'd like to get some opinions on the best/cleanest way
- to accomplish the following:
-
- I've got an object which has already been constructed
- via its default constructor which just sets all pointers
- to NULL. Whats the best way to deep-copy into it?
-
-
- class A {
- public:
- A(); // default ctor
- A(const A&) // copy ctor
- A(const char *) // convert ctor
- };
-
- somefunc()
- {
- ...
- A a0;
- ...
- A a1("blah");
-
- //
- // How do you deep copy a1 into a0 ???
- //
- a0 = a1; // no good. shallow copy
- a0 = A(a1); // no good. dtor called for temp A object
- a0 = *new A(a1); // no good. creates memory for a A object
-
- //
- // the follow works but is tedious
- //
- A empty; // create an empty object
- A tmp(a1); // deep-copy a1 to temp
- a0 = tmp; // shallow-copy temp to a0
- tmp = empty; // clear out temp so internals are not destructed
-
- //
- // so overload = to make deep copies
- //
- a0 = a1;
-
- }
-
- //
- // deep-copy =
- //
- A& A::operator =(const A& other)
- {
- A empty;
- A tmp(other);
- memcpy(this, &tmp, sizeof(A));
- memcpy(&tmp, &empty, sizeof(A));
- return *this;
- }
-
-
- I'd like to know what people think of the solution I've reached.
- I figure that this type of shit is common enough so there should
- be some widely accepted solution to this problem. Or maybe its
- not, but believe me that the situation does occur.
-
- Thanks,
- brien
-
-